<template>
  <view>
    <view v-if="data.length > 0">
      <!--支持多选-->
      <!-- <view v-if="type === 'multiple'">
        <view class="title-text" @click="selectedAll()"> 全选 </view>
        <view class="title-text" @click="toggle()"> 反选 </view>
        <view class="title-text" @click="cancelSelect()"> 清空 </view>
      </view> -->
      <view class="flex flex-wrap">
        <view
          v-for="(item, index) in data"
          :key="index"
          class="text-center text-xs border-common rounded-full h-7 leading-7 item-3-10 mb-3"
          @click="select(index)"
          :class="{
            activeIndex: selectedArr.indexOf(index) !== -1,
            'item-mx-5': index % 3 == 1,
          }"
        >
          {{ item.text }}
        </view>
      </view>
    </view>
    <view v-else class="text-center text-sm leading-8 text-gray"
      >- 暂无数据 -</view
    >
  </view>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      default: () => {
        return [];
      },
    },
    val: {
      type: Array,
      default: () => {
        return [];
      },
    },
    type: {
      type: String,
      default: 'single', //single单选   multiple 多选
    },
  },
  data() {
    return {
      selectedArr: [],
    };
  },
  watch: {
    val: {
      handler(val) {
        this.selectedArr = [];
        this.data.forEach((item, i) => {
          val.forEach((value) => {
            if (value === item.value) {
              this.selectedArr.push(i);
            }
          });
        });
        //console.log(this.selectedArr);
      },
      immediate: true,
    },
    selectedArr: {
      handler(val) {
        let arr = [];
        let textArr = [];
        val.forEach((el) => {
          arr.push(this.data[el].value);
          textArr.push(this.data[el].text);
        });
        this.$emit('update', arr, textArr);
      },
      deep: true,
    },
  },
  methods: {
    select(index) {
      if (this.type === 'single') {
        //单选
        if (this.selectedArr[0] !== index) {
          this.selectedArr = [];
          this.selectedArr.push(index);
        } else {
          this.selectedArr = [];
        }
      } else {
        //可多选
        let searchIndex = this.selectedArr.indexOf(index);
        if (searchIndex === -1) {
          this.selectedArr.push(index);
        } else {
          this.selectedArr.splice(searchIndex, 1);
        }
      }
    },
    /**
     * 全选
     */
    selectedAll() {
      this.selectedArr = Array(this.data.length)
        .fill(null)
        .map((_, index) => index);
    },
    /**
     * 反选
     */
    toggle() {
      let arr = Array(this.data.length)
        .fill(null)
        .map((_, index) => index);
      this.selectedArr = arr.filter((_item, _index, _arr) => {
        return this.selectedArr.indexOf(_item) === -1;
      });
    },
    /**
     * 清空选择
     */
    cancelSelect() {
      this.selectedArr = [];
    },
  },
};
</script>
<style></style>
